import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../models/hot_model.dart';

class BannerScreen extends StatefulWidget {
  const BannerScreen({super.key,  required this.banners});
  final List<BannerModel> banners;
  @override
  _BannerScreenState createState() => _BannerScreenState();
}

class _BannerScreenState extends State<BannerScreen>
    with SingleTickerProviderStateMixin {

  late PageController _pageController;
  late Timer _timer;
  final int autoSwitchDuration = 3000; // 自动切换时间间隔，单位为毫秒

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
    startAutoSwitch();
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  void startAutoSwitch() {
    _timer =
        Timer.periodic(Duration(milliseconds: autoSwitchDuration), (timer) {
      int currentPage = _pageController.page!.round();
      int nextPage = (currentPage + 1) % widget.banners.length;
      _pageController.animateToPage(nextPage,
          duration: Duration(milliseconds: 500), curve: Curves.easeInOut);
    });
  }

  void _handlePageChange(int page) {
    // 可以在这里处理页面变化，比如停止自动切换然后重新开始等
    // 但在这个例子中，我们保持自动切换持续进行
  }

  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      controller: _pageController,
      itemCount: widget.banners.length,
      onPageChanged: _handlePageChange,
      itemBuilder: (context, index) {

        return CachedNetworkImage(imageUrl: widget.banners[index].imgUrl, fit: BoxFit.fitWidth,);



      },
    );
  }
}
